package com.yonyou.iuap.jxzy.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.util.Base64Utils;

import com.yonyou.iuap.utils.Base64Util;

/**
 * 文件操作工具类
 * @author WXF
 *
 */
public class FileUtils {
	
	/**
	 * 读取文件内容
	 * @param filename : 文件路径
	 * @param charsetName ： 编码方式
	 * @return
	 * @throws IOException 
	 */
	public static final String getFileText(File file,String charsetName) throws IOException {
		InputStreamReader read = new InputStreamReader(new FileInputStream(file), charsetName);
		BufferedReader br = new BufferedReader(read);
		StringBuffer stest=new StringBuffer();
		try {
			//文件转换为InputStreamReader流
			String lineTxt = null;
			//按行读取文件并构造到stest字符串中
			while ((lineTxt = br.readLine()) != null) {
				stest.append(lineTxt);
			}
		} finally{
			br.close();//关闭访问连接
		}
		return stest.toString();
	}
	
	/**
	 * 向指定目录创建写数据
	 * @param text ：写入数据
	 * @param filename ：写入文件路径
	 * @throws IOException 
	 */
	public static final void writerFile(String text,String filename,String route) throws IOException{
		//创建文件夹输出
		File file = new File(route);
		if(!file.exists() && !file.isDirectory()) {
			file.mkdirs();//文件夹不存在，新增文件夹
		}
		file = new File(route+filename);
		if(!file.exists()){//如果不存在着创建
			file.createNewFile();
		}
		FileWriter fw = new FileWriter(file);//使用文件写入
		fw.write(text);
		fw.close();//关闭连接
	}
	
	public static void downZip(ExcelParam excelParam, HttpServletResponse response) throws IOException {
		byte[] content = Base64Utils.decodeFromString("aa");
        //设置文件名
        String fileName = excelParam.name + ".zip";
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
//        response.addHeader("Content-Length", "" + content.length);
        OutputStream outputStream = response.getOutputStream();
        outputStream.write(content);
        outputStream.flush();
        outputStream.close();
    }
	
}
